<template>
  <div class="company">
    <el-dialog :visible.sync="dialogFrom" @close="clear" width="1125px" :close-on-click-modal="false" :close-on-press-escape	='false'
               center :title="title" class="cust_dialog emailAddMan">
      <div class="dialog_content">
        <el-form ref="form" :model="form" labelPosition='left' label-width="88px" :size="size" :rules="rules"
                 class="edit_form">
          <div class="main_left">
            <p class="message">基本信息</p>
            <span style="margin-top:10px;display:inline-block;"></span>
            <!--          <el-form ref="form" :model="form"  labelPosition='right' label-width="90px" :size="size" :rules="rules">-->
            <el-row :gutter="20">
              <el-col :span="12" style="height: 40px">
                <div class="grid-content bg-purple" style="display: flex">
                  <el-form-item label="客户头像:">
                    <el-upload action=""
                               :http-request="uploadFile"
                               :multiple="false"
                               accept=".jpg,.png,.jpeg" :show-file-list=false >
                      <img v-if="form.logoUrl" :src="form.logoUrl" class="custLogo">
                      <span v-else
                            style="background-color:#DDDDDD;width: 50px;height: 50px;border-radius: 50%;display: inline-block "></span>
                    </el-upload>
                  </el-form-item>
                </div>
              </el-col>

              <el-col :span="12">
                <div class="grid-content bg-purple">
                  <el-form-item label="客户全称:" prop="fullname">
                    <el-input v-model="form.fullname"></el-input>
                  </el-form-item>
                </div>
              </el-col>

              <el-col :span="12">
                <div class="grid-content bg-purple">
                  <el-form-item label="所属行业:" prop="industry">
                    <el-input v-model="form.belongTo"></el-input>
                  </el-form-item>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="grid-content bg-purple">
                  <div class="classification">
                    <el-form-item label="主营业务:" prop="classify1" class="not_icon_label">
                      <el-cascader
                        style="width: 100%"
                        change-on-select
                        :props="{value:'id', label:'dictKey'}"
                        :show-all-levels="false"
                        v-model="industryId"
                        :options="industryOptions"></el-cascader>

                    </el-form-item>
                  </div>
                </div>
              </el-col>

              <el-col :span="12">
                <div class="grid-content bg-purple">
                  <el-form-item label="营业额:" prop="turnover">
                    <el-select v-model="form.turnOver" placeholder="请选择" style="width:100%">
                      <el-option
                        v-for="item in turnoverOptions"
                        :key="item.id"
                        :label="item.dictKey"
                        :value="item.id">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="grid-content bg-purple">
                  <div class="classification">
                    <el-form-item label="雇员数:" prop="number" class="not_icon_label">
                      <el-select v-model="form.persons" placeholder="请选择" style="width:100%">
                        <el-option
                          v-for="item in empleOptions"
                          :key="item.id"
                          :label="item.dictKey"
                          :value="item.id">
                        </el-option>
                      </el-select>
                    </el-form-item>
                  </div>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="grid-content bg-purple">
                  <el-form-item label="公司传真:" prop="fax">
                    <el-input v-model="form.fax" placeholder="号码只能包括数字、空格和符号"></el-input>
                  </el-form-item>
                </div>
              </el-col>

              <el-col :span="12">
                <div class="grid-content bg-purple">
                  <div class="classification">
                    <el-form-item label="公司座机:" prop="tel" class="not_icon_label">
                      <el-input v-model="form.tel"></el-input>
                    </el-form-item>
                  </div>
                </div>
              </el-col>

              <el-col :span="12">
                <div class="grid-content bg-purple">
                  <div>
                    <el-form-item label="业务员:" prop="manager" class="not_icon_label">
                      <span>{{salesmanName}}</span>
                    </el-form-item>
                  </div>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="grid-content bg-purple">
                  <el-form-item label="客户分组:" prop="classification">
                    <el-cascader
                      style="width: 100%"
                      :show-all-levels="false"
                      v-model="typeId"
                      :options="custTypeOptions"
                      change-on-select
                      :props="downProps"
                      clearable></el-cascader>
                  </el-form-item>
                </div>
              </el-col>

              <el-col :span="12">
                <div class="grid-content bg-purple">
                  <el-form-item label="地址:" prop="classification">
                    <el-select v-model="form.countryId" filterable placeholder="国家/地区" style="width:100%">
                      <el-option
                        v-for="item in countryOptions"
                        :key="item.id"
                        :label="`${item.countryEname} (${item.countryName})`"
                        :value="item.id">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </div>
              </el-col>

              <el-col :span="12">
                <div class="grid-content bg-purple">
                  <el-input v-model="form.addrs" placeholder="详细地址" size="medium"></el-input>
                </div>
              </el-col>

            </el-row>
            <el-form-item label="网址:" prop="website">
              <el-input v-model="form.website" style="width: 556px"></el-input>
            </el-form-item>
            <p class="message">管理信息</p>
            <el-row :gutter="20">
              <el-col :span="12">
                <div class="grid-content bg-purple">
                  <el-form-item label="客户类型:" prop="type">
                    <el-select v-model="form.bussType" placeholder="请选择" style="width:100%">
                      <el-option
                        v-for="item in companyTypeOptions"
                        :key="item.id"
                        :label="item.dictKey"
                        :value="item.id">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="grid-content bg-purple">
                  <el-form-item label="客户来源:" prop="source">
                    <el-select v-model="form.resourceId" placeholder="请选择" style="width:100%">
                      <el-option
                        v-for="item in sourceOptions"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </div>
              </el-col>

              <el-col :span="12">
                <div class="grid-content bg-purple">
                  <el-form-item label="客户标签:">
                    <el-select v-model="markIds" multiple placeholder="请选择" style="width:100%">
                      <el-option
                        v-for="item in markOptions"
                        :key="item.id"
                        :label="item.markName"
                        :value="item.id">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </div>
              </el-col>

              <el-col :span="12">
                <div class="grid-content bg-purple">
                  <el-form-item label="客户评级:" prop="grade">
                    <div class="editRate">
                      <el-rate v-model="form.gradeType"></el-rate>
                    </div>
                  </el-form-item>
                </div>
              </el-col>
              <el-col :span="24">
                <div class="grid-content bg-purple">
                  <el-form-item label="客户备注:" >
                    <div class="editRate">
                      <el-input v-model="form.remarks" style="width: 99%"  type="textarea"></el-input>
                    </div>
                  </el-form-item>
                </div>
              </el-col>
            </el-row>
            <div>
              <span class="message"
                    style="line-height:40px;display:inline-block;float:left;margin-right:20px;">社交网络</span>
              <div class="message_box" v-for="(itemVal, index) in form.custSocialDtos" :key="index">
                <el-select v-model="itemVal.socialType" size="medium" style="margin-right:15px;">
                  <el-option
                    v-for="item in socialOptions"
                    :key="item.id"
                    :label="item.dictKey"
                    :value="item.id">
                  </el-option>
                </el-select>
                <el-input v-model="itemVal.socialWebSite" placeholder="社交账号" style="width:332px" size="medium"></el-input>
                <span class="icon-delete_icon remove contact_icon" @click="remove(index)"
                      :class="index === 0 ? 'frist' : ''"></span>
              </div>
              <span class="social" @click="addSocial" onselectstart="return false;">新增社交网络</span>
            </div>
            <!--          </el-form>-->
          </div>
          <div class="main_right">
            <p class="message">联系人信息</p>
            <div v-if="dialogFrom">
              <div v-for="item,index in form.custLinkDtos" :key="index" style="margin-bottom: 10px">
                <el-form-item label="姓名：" :prop="`custLinkDtos[${index}].linker`"
                              :rules="{required: true, message: '请输入客户姓名', trigger: 'blur'}">
                  <el-input v-model="item.linker" width="220px"></el-input>
                  <span class="icon-delete_icon remove" @click="removeContacts(index, item)"
                        :class="index === 0 ? 'frist' : ''"></span>
                </el-form-item>
                <el-form-item label="邮 箱:" :prop="`custLinkDtos[${index}].email`" :rules="[
                  {required: true, message: '请输入客户邮箱', trigger: 'blur'},
                  { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }]">
                  <el-input v-model="item.email" style="width:220px" :size="size"></el-input>
                </el-form-item>
                <div class="classification">
                  <el-form-item label="职 位:" class="not_icon_label">
                    <el-input v-model="item.postType" style="width:220px" :size="size"></el-input>
                  </el-form-item>
                </div>
                <div class="classification">
                  <el-form-item label="联系电话:" :prop="`custLinkDtos[${index}].telFax`" :rules="rules.telFax"
                                class="not_icon_label">
                    <el-input v-model="item.telFax" style="width:220px" :size="size"></el-input>
                  </el-form-item>
                </div>

                <div class="classification">
                  <el-form-item label="社交平台:" :prop="`custLinkDtos[${index}].telFax`" :rules="rules.telFax" class="not_icon_label">
                    <el-select v-model="item.socialType" size="medium" style="width: 100%">
                      <el-option
                        v-for="item in socialOptions"
                        :key="item.id"
                        :label="item.dictKey"
                        :value="item.id">
                      </el-option>
                    </el-select>
                    <br/>
                    <el-input v-model="item.socialAccount" style="width:220px;margin-top: 10px" :size="size" placeholder="账号"></el-input>
                  </el-form-item>
                </div>

                <div class="classification">
                  <el-form-item label="备注:" :prop="`custLinkDtos[${index}].remarks`" class="not_icon_label">
                    <el-input v-model="item.remarks" style="width:220px" :size="size"></el-input>
                  </el-form-item>
                </div>
                <div class="classification">
                  <el-form-item label="主联系人:" :prop="`custLinkDtos[${index}].mainly`" class="not_icon_label">
                    <el-switch
                      v-model="item.mainly"
                      :active-value="1"
                      :inactive-value="0">
                    </el-switch>
                  </el-form-item>
                </div>
              </div>
            </div>
            <div>
            </div>
            <span class="social" @click="addContacts(form.custLinkDtos)">+添加联系人</span>
            <!--            <div class="submitBtn">-->
            <!--              <el-button @click="clear()" size="medium" type="primary" plain>取 消</el-button>-->
            <!--              <el-button type="primary" @click="submit('form')" size="medium">保 存</el-button>-->
            <!--            </div>-->
          </div>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer" align="right">
        <el-button @click="clear()" size="small">取 消</el-button>
        <el-button type="primary" size="small" @click="submit('form')" :loading="loading">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
    import {
        saveCust,
        queryCustType,
        editCust,
        queryCustMark,
        getSourceList
    } from '@/api/customer' // 增 改
    import {uploadOss} from '@/util/file'
    import {mapGetters, mapState} from 'vuex'

    export default {
        props: ['title', 'defaultType', 'currentEmail'],
        data() {
            var checkphone = (rule, value, callback) => {
                const reg = /^[0-9,+ \-,\\(,\\),x,!,#,$,%,^,&,*,|,?,\s]*$/
                if (reg.test(value)) {
                    callback();
                } else {
                    return callback(new Error('电话号码只能包括数字、空格和符号'));
                }
            };
            return {
                loading:false,
                value1: [],
                dialogFrom: false,
                size: 'medium',
                salesmanName: '',
                form: {
                    fullname: '', // 公司全称
                    shortname: '', // 工作简称
                    belongTo: '', // 所属行业
                    industryId: '', // 行业分类
                    turnOver: '', // 营业额
                    persons: '', // 雇员数
                    fax:'', // 传真
                    tel: '', // 电话
                    manager: '', // 业务员
                    typeId: '', // 客户分组id
                    relation: '', // 客户分组层级关系
                    quickAccount: '', // 快速账号
                    website: '', // 网址
                    bussType: '', // 公司类型
                    resourceId: '', // 公司来源
                    gradeType: 0, // 公司评级
                    corpid: '',
                    addrs: '', // 详细地址
                    countryId: '', // 国家id
                    countryName: '', // 国家中文名
                    countryIcon: '', // 国家英文名
                    custSocialDtos: [ // 社交网络
                        {
                            socialType: "",
                            socialWebSite: ""
                        }
                    ],
                    logoUrl: '',
                    custLinkDtos: [ // 联系人
                        {
                            linker: "",
                            email: "",
                            postType: "",
                            telFax: "",
                            socialType:"",
                            socialAccount: "",
                            mainly:1,
                            remarks: ""
                        }
                    ],
                    custDelLinkDtos: []
                },
                industryId: [], //行业分类
                header: {},
                typeId: [],  // 分组id集合
                relation: [], // 客户分组层级关系
                rules: {
                    fullname: [
                        {required: true, message: '请输入公司全称', trigger: 'blur'}
                    ],
                    shortname: [
                        {required: true, message: '请输入公司简称', trigger: 'blur'}
                    ],
                    tel: [
                        {validator: checkphone, trigger: 'blur'}
                    ],
                    fax:[
                        {validator: checkphone, trigger: 'blur'}
                    ]
                },
                empleOptions: [], // 雇员数数组
                turnoverOptions: [], // 营业额数组
                companyTypeOptions: [], // 公司类型
                sourceOptions: [], // 公司来源
                industryOptions: [], // 行业分类
                industryOptions1: [], // 行业分类联动
                socialOptions: [], // 社交网络
                chargeOptions: [], // 业务员
                custTypeOptions: [], // 客户分类列表
                countryOptions: [], // 国家地区列表
                socialItem: [{
                    id: 0,
                    value: ''
                }],
                typeProps: {
                    value: 'id',
                    label: 'text'
                },
                userId: '',
                custTypeProps: {
                    value: 'id',
                    label: 'folderName'
                },
                salesman: [],
                defaultId: '',
                selectProps: {
                    label: 'dictKey',
                    value: 'id'
                },
                menuIcon: 'el-icon-arrow-down',
                showMenu: false,
                downProps: {
                    value: 'id',             // ID字段名
                    label: 'text',         // 显示名称
                    children: 'children'    // 子级字段名
                },
                valueTitle: '',
                selectValue: '',
                markOptions: [], // 标签集合
                markIds:[], // 标签选中集合
            }
        },
        computed: {
            ...mapGetters(['userInfo']),
            ...mapState(['common']),
            countryId() {
                return this.form.countryId
            },
        },
        mounted() {
            //start - 初始化邮件客户信息
            this.dealInit(this.currentEmail);
            // end
            document.body.addEventListener('click', () => {
                this.showMenu = false
                this.bus.$emit('closeMenu')
            })
        },
        methods: {
            init(email) {
                this.getInit();
                this.form.logoUrl = '';
                this.dialogFrom = true;
                this.dealInit(email);
            },
            dealInit(email) {
                this.form.custLinkDtos = [{
                    linker: "",
                    email: email,
                    postType: "",
                    telFax: "",
                    mainly:1,
                    remarks: ""
                }]
                this.form.custSocialDtos = [
                    {
                        socialType: "",
                        socialWebSite: ""
                    }
                ]
            },
            getInit() {
                this.userId = this.userInfo.user_id;
                this.salesmanName = this.userInfo.account;
                this.form.manager = this.userId;
                this.turnoverOptions = this.common.turnoverOptions
                this.companyTypeOptions = this.common.companyTypeOptions
                this.industryOptions = this.common.industryOptions
                this.socialOptions = this.common.socialOptions
                this.empleOptions = this.common.empleOptions
                this.countryOptions = this.common.countryOptions

                queryCustType().then((res) => {
                    if (res.data.success) {
                        this.custTypeOptions = res.data.data
                        if (this.$route.params.typeId && this.id == '') {
                            this.typeId = this.dealID(this.custTypeOptions, this.$route.params.typeId)
                        }
                    }
                })

                queryCustMark(this.form.manager).then(res => {
                    if (res.data.success) {
                        this.markOptions = res.data.data
                    }
                })

                //       客户来源
                getSourceList().then(res => {
                    if (res.data.success) {
                        this.sourceOptions = res.data.data
                    }
                })

            },
            clear() {
                this.dialogFrom = false;
                this.$refs.form.resetFields();
                this.salesmanName = ''
                this.markOptions = []
            },
            setSectionValue(value) { // 设置value
                this.form.typeId = value
            },
            openDown() { // 打开下拉
                if (this.menuIcon == 'el-icon-arrow-down') {
                    this.menuIcon = 'el-icon-arrow-up'
                    this.showMenu = true
                } else {
                    this.menuIcon = 'el-icon-arrow-down'
                    this.showMenu = false
                }
            },
            checkClick(data, value) { // 复选框点击
                // this.valueTitle = value.data.id
                this.defaultId = value.data.id
                this.form.typeId = value.data.id
                this.showMenu = false
                this.menuIcon = 'el-icon-arrow-down'
            },
            submit(formName) { // 判断是编辑，还是新增
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        this.loading = true
                        this.form.industryId = this.industryId[this.industryId.length - 1]
                        this.form.typeId = this.typeId[this.typeId.length - 1]
                        this.form.markIds = this.markIds != [] ? this.markIds.join(',') : ''
                        if (this.title == '编辑客户') {
                            editCust(this.form).then(res => {
                                if (res.data.success) {
                                    this.$message({
                                        type: 'success',
                                        message: res.data.msg
                                    })
                                    this.loading = false
                                    this.$emit('relationCustomer')
                                }
                            }).catch(()=> {
                                this.loading = false
                            })
                            this.dialogFrom = false;
                        } else {
                            saveCust(this.form).then((res) => {
                                if (res.data.success) {
                                    this.$message({
                                        type: 'success',
                                        message: res.data.msg
                                    })
                                    this.bus.$emit('refreshEmailGet');
                                    this.$emit('relationCustomer')
                                    this.dialogFrom = false;
                                    this.loading = false
                                }
                            }).catch(()=> {
                                this.loading = false
                            })
                        }

                    } else {
                        return false
                    }
                })
            },
            uploadFile(File) {
                let file = File.file;
                uploadOss(file).then(result => {
                    if(result.hasOwnProperty('url')){
                        this.form.logoUrl = result.url
                    }else{
                        this.$message({
                            type: "success",
                            message: '头像上传失败,请重新上传!'
                        })
                    }
                }).catch(err => {
                    this.$message({
                        type: "success",
                        message: '头像上传失败,请重新上传!'
                    })
                })
            },
            addContacts() { // 增加联系人
                this.$nextTick(() => {
                    let obj = {
                        "linker": "",
                        "email": "",
                        "postType": "",
                        "telFax": "",
                        "socialType":"",
                        "socialAccount": "",
                        "mainly":0,
                        "remarks": ""
                    }
                    this.form.custLinkDtos.push(obj)
                })
            },
            removeContacts(index, item) { // 删除联系人数组项
                if (index !== 0) {
                    this.form.custLinkDtos.splice(index, 1)
                    if (this.title === '编辑客户') {
                        this.form.custDelLinkDtos.push(item)
                    }
                }
            },
            addSocial() {
                this.form.custSocialDtos.push({
                    "socialType": "",
                    "socialWebSite": ""
                })
            },
            remove(index) {
                if (index !== 0) {
                    // this.socialItem[index]['id'] = ''
                    this.form.custSocialDtos.splice(index, 1)
                }
            },
            dealID(tree, targetID) {
                let parentList = []

                function buildParentList(arr) {
                    arr.forEach(g => {
                        if (g.pid != undefined) {
                            let pid = g['pid']
                            let oid = g['id']
                            parentList[oid] = pid
                        }
                        if (g.children != undefined && g.children.length != 0)
                            buildParentList(g['children'])
                    })
                }

                buildParentList(tree)
                let arr = []
                var newArr = []

                function findParent(idx) {
                    if (parentList[idx] != undefined) {
                        let pid = parentList[idx]
                        arr.push(pid)
                        findParent(pid)
                    } else {
                        arr.reverse()
                        arr.splice(0, 1)
                        newArr = arr
                    }
                }

                findParent(targetID)
                newArr.push(targetID)
                return newArr;
            }
        },

        watch: {
            countryId(value) {
                this.countryOptions.forEach((v) => {
                    if (v.id == value) {
                        this.form.countryName = v.countryName
                        this.form.countryIcon = v.countryEname
                    }
                })
            },
            'form.salesman': function (value) {
                this.form.manager = value[value.length - 1]
            },
            valueTitle(value) {
                this.defaultId = value
            }
        }
    }
</script>

<style lang="scss">
  .editRate {
    .el-rate__icon {
      font-size: 25px;
    }
  }

  .cust_dialog {
    .el-dialog {
      background-color: #F5F5F5;
      height: 700px;
    }
    .el-dialog__body{
      height: calc(100% - 50px);
    }
  }
  .classification{
    .not_icon_label{
      label{
        padding-left: 10px;
      }
    }
  }
</style>

<style scoped lang="scss">
  .title {
    color: #409eff;
    text-align: center;
  }

  .message {
    color: #409eff;
    line-height: 26px;
    font-weight: 600;
  }

  .message_box {
    float: left;
    display: flex;
    position: relative;
    margin-bottom: 10px;
    margin-left: 77px;
  }

  .social {
    text-decoration: underline;
    line-height: 20px;
    overflow: hidden;
    cursor: pointer;
    margin-top: 10px;
    display: inline-block;
  }

  .main_left {
    float: left;
    width: 650px;
    margin-right: 20px;
    font-size: 13px !important;
    background-color: white;
    padding: 20px;
    border-radius: 10px;
  }

  .main_right {
    float: left;
    font-size: 13px !important;
    background-color: white;
    padding: 20px;
    padding-right: 30px;
    border-radius: 10px;
  }

  .el-dialog__body {
    overflow: hidden !important
  }

  .lable {
    text-align: right;
    display: inline-block;
    width: 80px
  }

  .message_item {
    margin-bottom: 22px;
    position: relative;
  }

  .contact_title {
    color: #409eff;
  }

  .remove {
    position: absolute;
    right: -25px;
    font-size: 18px;
    cursor: pointer;
  }

  .contact_icon {
    top: 5px;
  }

  .company {
    font-size: 13px !important;
  }
  .submitBtn {
    position: absolute;
    bottom: 15px;
    right: 40px;
  }

  .frist {
    color: #DDDDDD;
  }

  .custLogo {
    height: 40px;
    width: 40px;
    border-radius: 50%;
  }

  .upload-demo {
    display: inline-block;
    margin-left: 20px;
  }

  .downBox {
    border: 1px solid #DCDFE6;
    border-radius: 4px;
    box-sizing: border-box;
    width: 100%;
    max-height: 200px;
    overflow: scroll;
    position: absolute;
    z-index: 100;
    background: white;
    /*height: 100%;*/
  }
</style>
